<template>
  <!--添加产品-->
  <section class="component edit-product">
    <el-form :model="model" :rules="rules" ref="edit-product" label-width="130px">
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model.trim="model.productName"></el-input>
      </el-form-item>
      <el-form-item label="产品内容" prop="productContent">
        <el-input type="textarea" v-model.trim="model.productContent" :autosize="{ minRows:2, maxRows:4}" :maxlength="50"></el-input>
      </el-form-item>
      <el-form-item label="产品价格" prop="productPrice">
        <el-input type="number" v-model="model.productPrice"></el-input> 元
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" v-model.trim="model.remark" :autosize="{ minRows:2, maxRows:4}" :maxlength="50"></el-input>
      </el-form-item>
      <el-form-item label-width="0px">
        <el-row type="flex" justify="center">
          <el-button @click="close()">取消</el-button>
          <el-button @click="confirm()">确定</el-button>
        </el-row>
      </el-form-item>
    </el-form>
  </section>
</template>

<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'
import { Dependencies } from '~/core/decorator'
import { Prop, Emit } from 'vue-property-decorator'
import { ProductService } from '~/service/service-product/product.service'

@Component({})
export default class EditProduct extends Vue {
  @Dependencies(ProductService)
  private productService: ProductService
  @Prop()
  private productInfo: any

  // 添加产品数据模型
  private model: any = {
    productName: '',
    productContent: '',
    productPrice: '',
    remark: ''
  }

  private rules: any = {
    productName: [{required: true, message: '请输入产品名称', trigger: 'blur'}],
    productContent: [{required: true, message: '请输入产品内容', trigger: 'blur'}],
    productPrice: [{required: true, message: '请输入价格', trigger: 'blur'}]
  }

  @Emit('close')
  public close() {}
  @Emit('refreshData')
  public refreshData() {}

  /**
   * 确定
   */
  private confirm() {
    let addForm: any = this.$refs['edit-product']
    addForm.validate((valid)=> {
      if (valid) {
        const v = {...this.model}
        v.id = this.productInfo.id
        this.productService.updateProduct(v).subscribe(
          data => {
            this.refreshData()
            this.close()
            this.$message.success('编辑成功')
          },
          error => this.$message.error(error.msg)
        )
      }
    })
  }

  private refresh() {
    this.model.productName = this.productInfo.productName
    this.model.productContent = this.productInfo.productContent
    this.model.productPrice = this.productInfo.productPrice
    this.model.remark= this.productInfo.remark
  }
}
</script>
